<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/20
 * Time: 10:24
 */
namespace app\wechat\controller;

use app\common\controller\BaseController;
use app\wechat\service\ArticleService;
use app\wechat\service\UserFavoriteService;
use think\Request;

class Article extends BaseController {
    private $per_page;

    public function __construct() {
        parent::__construct();
        $this->per_page = config('wx_config')['per_page'];
    }

    public function index()
    {
        $id = 7;
        $id |= 11;
        dump($id);
        dump(pow(2, 26));
        dump(0x1);
        halt(0x1 << intval(log(99999999)/log(2)));
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     * 获取文章列表
     */
    public function getArticleList(Request $request) {
        $where = [];
        $page = $request->post('page', '1', 'int');
        $category_id = $request->post('category_id', '', 'int');
        if (!empty($category_id)) {
            $where['category_id'] = $category_id;
        }
        $this->per_page=4;
        $limit = ($page - 1) * $this->per_page . ',' . $this->per_page;
        $list = ArticleService::getArticleList($where, $limit);
        $total_page = ceil($list['total'] / $this->per_page);
        $next_page = ($page >= $total_page) ? $total_page : bcadd($page, 1);
        $previous_page = ($page <= 1) ? $page : bcsub($page, 1);
        $list['per_page'] = $this->per_page;
        $list['page'] = $page;
        $list['next_page'] = $next_page;
        $list['previous_page'] = $previous_page;
        $list['total_page'] = $total_page;
        return json($list);
    }

    public function getArticleDetail(Request $request) {
        $article_id = $request->post('article_id', '', 'int');
        $where['id'] = $article_id;
        $list = ArticleService::getArticleDetail($where);
        return json($list);
    }

    public function addUserFavoriteArticle(Request $request) {
        $data = $request->post();
        $result = $this->validate($data,'UserFavorite.add');
        if(true !== $result){
            // 验证失败 输出错误信息
            return $this->successJson($result);
        }
        $res = UserFavoriteService::saveUserFavorite($data);
        if($res['code'] == '000000'){
            //成功
            return $this->successJson($res['msg']);
        } else {
            //失败
            return $this->errorJson($res['msg'], $res['code']);
        }
    }
}